<template>
  <view class="main">
    <up-swipe-action
        @click="handleSwipeAction"
    >
      <up-swipe-action-item
        class="swipe-action-item"
        :options="options"
        v-for="(item, index) in queryResult.list"
        :key="item.id"
        :index="index"
        :name="index"
        @click="handleSwipeActionItem"
      >
        <view class="cart-item">
          <view class="left" @click.stop="handleCartItem(item)">
            <view class="cart-checkbox" :class="{'active': selectedCartIds.includes(item.id)}">
              <text class="iconfont icon-selected"></text>
            </view>
          </view>
          <ProductOrder class="product-item" :product="item" >
            <template #extar>
              <view class="number-box">
                <up-number-box v-model="item.productAmount" @change="(e)=> handleNumChange(e, item)" :min="1" :max="100" integer>
                  <template #minus>
                    <view class="input-btn minus"> <text class="iconfont icon-minus"></text></view>
                  </template>
                  <template #input>
                    <text class="input" >{{item.productAmount}}</text>
                  </template>
                  <template #plus>
                    <view class="input-btn  plus"><text class="iconfont icon-plus"></text></view>
                  </template>
                </up-number-box>
              </view>
            </template>
          </ProductOrder>
        </view>
      </up-swipe-action-item>
    </up-swipe-action>
    <Empty v-if="queryResult.isQueryed && !queryResult.list.length"/>
    <view class="footer">
      <view class="footer-content">
      <view class="footer-left" @click="handleSelectAll">
        <view class="cart-checkbox" :class="{'active': isSelectedAll}">
          <text class="iconfont icon-selected"></text>
        </view>
        <view class="">全选</view>
      </view>
      <view class="footer-right">
        <view class="footer-total">
          <text>合计：</text>
          <view class="price">
            <text v-if="props.type === 1">￥</text> 
            <text class="integer-price">{{priceData.integerPrice}}</text>
            <text class="decimal-price" v-if="priceData.decimalPrice !== 0">{{priceData.decimalPrice}}</text>
            <text v-if="props.type === 2">积分</text> 
          </view>
        </view>
        <view class="footer-btn" @click="handleSubmit">提交订单</view>
      </view>
      </view>

    </view>
    <TabBar :type="props.type"></TabBar>
    <Login />
  </view>
</template>

<script setup>
import { reactive, ref, computed, defineProps, defineEmits, defineExpose,  onMounted, watch} from 'vue'
import { useStore } from 'vuex'
import { onLoad, onReachBottom, onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { getCartListApi } from '@/api/user'
import ProductOrder from "@/components/product/ProductOrder.vue";
import {updateCartApi} from "@/api/user";
const props = defineProps({
  type: Number,
  default: 1
})
const emits = defineEmits(['mounted'])
const store = useStore()
const isLogin = computed(()=> {
  return store.state.user.isLogin
})
watch(
  () => isLogin.value,
  (v) => {
    v && init()
  },
);
const options = reactive([
  {  
    text: '删除',  
    style: {  
      backgroundColor: '#f56c6c'  
    }  
  }  
])
const queryResult= reactive({
  isLast: false,
  isQueryed: false,
  list: []
})
const queryData = reactive({
  page: 1,
  size: 10,
  type: props.type,
})
const selectedCartIds = ref([])

const totalPrice = computed(()=> {
  const ids = selectedCartIds.value
  let price = 0
  queryResult.list.forEach(item=> {
    if(ids.includes(item.id)) {
      price += item.productAmount * item.price
    }
  })
  return Number(price.toFixed(2))
})

const priceData = computed(()=> {
  if(totalPrice.value) {
    const price = totalPrice.value.toFixed(2)
    const [ integerPrice, decimalPrice] = price.split('.')
    // return price.split('.')[0]
    return {
      integerPrice,
      decimalPrice: '.' + decimalPrice
    }
  }
  return  {
    integerPrice: 0,
    decimalPrice: 0,
  }
})
const isSelectedAll = computed(()=> {
  const list = queryResult.list
  if(list.length && list.length === selectedCartIds.value.length) {
    return true
  }
  return false
})
onMounted(()=> {
  emits('mounted')
})

async function init() {
  queryData.page = 1;
  queryResult.isLast = false
  await getListData()
}
async function loadNextPage(){
  if(queryResult.isLast) {
    return
  }
  queryData.page += 1;
  getListData()
}
async function getListData(){
  uni.showLoading()
  const res = await getCartListApi(queryData).finally(()=> {
    uni.hideLoading()
    queryResult.isQueryed = true
  })
  if(queryData.page === 1) {
    queryResult.list = [...res.items]
  } else {
    queryResult.list.push(...res.items)
  }
  queryResult.isLast = queryResult.list.length === res.total
 
}
async function handleSwipeActionItem(e){
  console.log(e)
  const { name } = e
  const item = queryResult.list[name]
  uni.showLoading()
  await updateCartApi({id: item.id, status: 0}).finally(()=> {
    uni.hideLoading()
  })
  init()
  // uni.l
}
function handleSwipeAction(e){
  console.log(e)
}
function handleCartItem(data) {
  const list = queryResult.list
  const index = selectedCartIds.value.indexOf(data.id)
  // debugger
  if(index >= 0) {
    selectedCartIds.value.splice(index, 1)
  } else {
    selectedCartIds.value.push(data.id)
  }
}
function handleSelectAll() {
  const list = queryResult.list
  if(list.length === selectedCartIds.value.length) {
    selectedCartIds.value = []
  } else {
    selectedCartIds.value = list.map(item => item.id)
  }
}
async function handleNumChange(e, item) {
  console.log(e, item.productAmount)
  uni.showLoading()
  await updateCartApi({id: item.id, productAmount: e.value || 1}).finally(()=> {
    uni.hideLoading()
    setTimeout(()=>{
      queryResult.isQueryed = true
    })
  })
  init()
}
function handleSubmit() {
  if(!selectedCartIds.value.length) {
    uni.showToast({
      icon: "none",
      title: '请选择购买产品'
    })
    return
  }
  uni.navigateTo({
    url: `/subpkgs/order/submit?type=${props.type}&cartIds=${selectedCartIds.value.toString()}`
  })
}
defineExpose({
  init: init,
  loadNextPage
})
</script>

<style lang='scss' scoped>
.main{
  min-height: 100vh;
  background: #F4F6F8;
  padding-top: 20rpx;
  padding-bottom: 140rpx;
  .cart-checkbox{
    display: flex;
    width: 40rpx;
    height: 40rpx;
    align-items: center;
    justify-content: center;
    background: #EEEEEE;
    border: 2rpx solid #EEEEEE;
    color: #fff;
    border-radius: 50%;
    .iconfont{
      display: none;
    }
    &.active{
      border: 2rpx solid #FF8F1F;
      background: #FF8F1F;
      .iconfont{
        display: inline;
      }
    }
  }
  .swipe-action-item{
    margin-bottom: 20rpx;
  }
  :deep(.u-swipe-action-item) {
    margin-bottom: 20rpx;
  }
  .cart-item {
    height: 204rpx;
    background: #FFFFFF;
    padding: 32rpx 24rpx 32rpx 0rpx;
    display: flex;
    //margin-bottom: 20rpx;
    .left{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 104rpx;
      .item-checkbox{

      }
    }
    .product-item{
      flex: 1;
    }
    .minus,.plus {
      width: 44rpx;
      height: 44rpx;
      border-radius: 4rpx 4rpx 4rpx 4rpx;
      border: 1rpx solid #EEEEEE;
      @include flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      color: #333333;
    }

    .input {
      width: 60rpx;
      height: 44rpx;
      line-height: 42rpx;
      text-align: center;
      border-top: 1rpx solid #EEEEEE;
      border-bottom: 1rpx solid #EEEEEE;
      box-sizing: border-box;
      color: #333333;
    }
  }
  .footer{
    position: fixed;
    bottom: 120rpx;
    left: 0;
    box-sizing: content-box;
    padding-bottom: var(--safe-area-inset-bottom);
    background: #FFFFFF;

    .footer-content{
      width: 100vw;
      height: 120rpx;
      display: flex;
      padding: 24rpx 0;
      justify-content: space-between;
      align-items: center;
    }
    .footer-left{
      padding: 0 32rpx;
      display: flex;
      font-weight: 400;
      font-size: 26rpx;
      color: #333333;
      line-height: 36rpx;
      align-items: center;
      gap: 12rpx;
      .checkbox{
        width: 40rpx;
        height: 40rpx;
        background: #EEEEEE;
        border: 2rpx solid #999999;
        margin-right: 12rpx;
      }
    }
    .footer-right{
      display: flex;
      padding-right: 32rpx;
      // flex: 1;
      .footer-total{
        display: flex;
        margin-right: 36rpx;
        align-items: center;
        font-weight: 400;
        font-size: 26rpx;
        color: #333333;
        .price{
          font-weight: 400;
          font-size: 24rpx;
          color: #FA5151;
          line-height: 36rpx;
          .integer-price{
            font-size: 48rpx;
            margin-left: 5rpx;
          }
          .decimal-price{
            font-size: 32rpx
          }
        }
      }
      .footer-btn{
        width: 180rpx;
        height: 72rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #EE0A24;
        border-radius: 55rpx;
        font-size: 26rpx;
        color: #FFFFFF;
      }
    }
  }
}
</style>
